﻿#include "mainwindow.h"

#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLayoutItem>
#include <QMessageBox>
#include <QDebug>
#include <QDesktopWidget>
#include <gsettingmonitor.h>
#include <QSettings>
#include "tipwidget.h"
#include "generatetools.h"
#include "config.h"

#define KYLIN_MOBILE_MOUNTFTP_PATH "/"
#define KYLIN_MOBILE_MOUNTFTP_SERVICE "com.kylin.mobile.assistant.mountftp"
#define KYLIN_MOBILE_MOUNTFTP_INTERFACE "com.kylin.mobile.assistant.mountftp"

const int USBPORT = 27183;
const int WIFIPORT = 27186;
const int USB_FTP_PORT = 27184;
const int WIFI_FTP_PORT = 27187;
const QString USB_FTPURL = "127.0.0.1";

MainWindow *MainWindow::getInstance()
{
    static MainWindow instance;
    return &instance;
}

QString MainWindow::getDeviceName()
{
    return m_connectInfo.deviceName;
}

void MainWindow::list(QString path)
{
    if (!m_isDbusOperation) {
        // 手机存储埋点
        GenerateTools::buriedPoint(kabase::BuriedPoint::PT::KylinMobileAssistantMobileStorage);
        qInfo() << "External request file list information.";
        m_isDbusOperation = true;
        m_ftpClient->list(path);
    }
}

void MainWindow::downFile(const QList<FileInfo> &fileList, QString downloadPath)
{
    if (!m_isDbusOperation) {
        // 下载文件埋点
        GenerateTools::buriedPoint(kabase::BuriedPoint::PT::KylinMobileAssistantMobileStorage);
        qInfo() << "External requests to download the file.";
        m_isDbusOperation = true;
        m_ftpClient->downAllFiles(fileList, downloadPath);
    }
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    Q_UNUSED(event);
    this->hide();
    if (m_isConnect) {
        slotDisconnect();
    }
}

void MainWindow::keyPressEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_F1) {
        m_titlebar->initHelp();
    }
    QWidget::keyPressEvent(event);
}

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
{
    qRegisterMetaType<QMap<QString, FileInfo>>("QMap<QString,FileInfo>");
    initService();
    initUI();
    initGsetting();
    initDbus();
}

MainWindow::~MainWindow()
{
    deleterUI();
    deleterService();
}

void MainWindow::initService()
{
    m_connectionService = new ConnectionService(this);
    connect(m_connectionService, &ConnectionService::sigConnectInfo, this, &MainWindow::slotConnect);
    connect(m_connectionService, &ConnectionService::sigDisconnect, this, &MainWindow::slotDisconnect);
    connect(m_connectionService, &ConnectionService::sigNotFountApk, this, &MainWindow::slotNotFountApk);

    // 监听USB插拔信号
    m_usbManage = new UsbManage;
    connect(m_usbManage, &UsbManage::sigVolumeConnected, this, &MainWindow::slotVolumeConnected);
    connect(m_usbManage, &UsbManage::sigVolumeDisconnected, this, &MainWindow::slotVolumeDisconnected);

    // 监听wifi
    m_wifiManager = new WifiManager;
    connect(m_wifiManager, &WifiManager::sigWifiConnected, this, &MainWindow::slotWifiConnected);
    connect(m_wifiManager, &WifiManager::sigWifiDisconnected, this, &MainWindow::slotWifiDisConnected);

    m_wifiManagerThread = new QThread;
    m_wifiManager->moveToThread(m_wifiManagerThread);

    connect(m_wifiManagerThread, &QThread::started, m_wifiManager, &WifiManager::startWifiInfo);

    m_wifiManagerThread->start();

    m_dbusInterface = new QDBusInterface(KYLIN_MOBILE_MOUNTFTP_SERVICE, KYLIN_MOBILE_MOUNTFTP_PATH,
                                         KYLIN_MOBILE_MOUNTFTP_INTERFACE, QDBusConnection::systemBus(), this);
    QObject::connect(m_dbusInterface, SIGNAL(sigMountError(bool, QString)), this, SLOT(slotMountError(bool, QString)));
}

void MainWindow::initGsetting(void)
{
    /* 主题 */
    QString themeStr = kdk::GsettingMonitor::getSystemTheme().toString();
    if (themeStr == QString("ukui-dark") || themeStr == QString("ukui-black")) {
        changeDarkTheme();
    } else {
        changeLightTheme();
    }
    connect(kdk::GsettingMonitor::getInstance(), &kdk::GsettingMonitor::systemThemeChange, this, [=]() {
        QString themeStr = kdk::GsettingMonitor::getSystemTheme().toString();
        if (themeStr == QString("ukui-dark") || themeStr == QString("ukui-black")) {
            changeDarkTheme();
        } else {
            changeLightTheme();
        }
    });

    return;
}

void MainWindow::initDbus()
{
    QDBusConnection sessionBus = QDBusConnection::sessionBus();
    if (!sessionBus.registerService(KYLIN_MOBILE_ASSISTANT_DBUS_SERVICE)) {
        qInfo() << "init dbus fail...";
        return;
    }
    sessionBus.registerObject(KYLIN_MOBILE_ASSISTANT_DBUS_PATH, this, QDBusConnection::ExportAllSlots);
}

void MainWindow::disconnectScreen()
{
    // 断开连接
    if (m_deviceManage != nullptr) {
        // 清空设备名
        delete m_deviceManage;
        m_deviceManage = nullptr;
    }
}

void MainWindow::disconnectFtp()
{
    if (m_ftpClient != nullptr) {
        if (m_isMountFtp) {
            umountFtp(MOUNT_DIR);
            m_isMountFtp = false;
        }
        delete m_ftpClient;
        m_ftpClient = nullptr;
    }
}

void MainWindow::stopAllDown()
{
    if (m_fileSyncManage != nullptr) {
        m_fileSyncManage->abortDown();
        delete m_fileSyncManage;
        m_fileSyncManage = nullptr;
    }
}

void MainWindow::disconnectService()
{
    stopAllDown();
    disconnectScreen();
    disconnectFtp();
    if (m_connectionService != nullptr) {
        m_connectionService->abortService();
    }
    m_isServerConnect = false;
}

void MainWindow::deleterService()
{
    if (m_usbManage != nullptr) {
        m_usbManage->deleteLater();
        m_usbManage = nullptr;
    }
    if (m_wifiManager != nullptr) {
        m_wifiManager->deleteLater();
        m_wifiManager = nullptr;
    }
    if (m_wifiManagerThread != nullptr) {
        m_wifiManagerThread->quit();
        m_wifiManagerThread->wait();
        m_wifiManagerThread->deleteLater();
        m_wifiManagerThread = nullptr;
    }
}

bool MainWindow::mountFtp(QString url, QString userName, QString pwd, QString path)
{
    if (m_dbusInterface->isValid()) {
        qInfo() << "Start mounting FTP...";
        m_dbusInterface->call("mountFtp", url, userName, pwd, path);
        return true;
    }
    return false;
}
bool MainWindow::umountFtp(QString path)
{
    if (m_dbusInterface->isValid()) {
        qInfo() << "Start umounting FTP...";
        m_dbusInterface->call("umountFtp", path);
        return true;
    }
    return false;
}

void MainWindow::clearConnectionInfo()
{
    m_connectInfo.uuid.clear();
    m_connectInfo.deviceName.clear();
    m_connectInfo.address.clear();
    m_connectInfo.connectType = ConnectionService::ConnectType::NOTCONNECT;
    m_connectInfo.usernamePwd.username.clear();
    m_connectInfo.usernamePwd.pwd.clear();
}

void MainWindow::changeLightTheme()
{
    qInfo() << "changeLightTheme";
    m_initConnectWin->setLightUI();
    m_connectedTitleWin->setLightUI();
}

void MainWindow::changeDarkTheme()
{
    qInfo() << "changeDarkTheme";
    m_initConnectWin->setDarkUI();
    m_connectedTitleWin->setDarkUI();
}

void MainWindow::initUI()
{
    setFixedSize(920, 640);
    setWindowTitle(tr("mobile-assistant"));
    m_titlebar = new Titlebar();
    m_initConnectWin = new InitConnectWin();
    m_connectedTitleWin = new ConnectedTitleWin();
    m_mobileFileList = new MobileFileList();
    m_stackedWin = new QStackedWidget();
    m_stackedMobileFileListWin = new QStackedWidget();

    m_stackedMobileFileListWin->addWidget(m_mobileFileList);
    m_stackedMobileFileListWin->setCurrentIndex(0);

    QVBoxLayout *layout = new QVBoxLayout;
    layout->addWidget(m_connectedTitleWin);
    layout->addWidget(m_stackedMobileFileListWin);

    QWidget *widget1 = new QWidget();
    widget1->setLayout(layout);

    m_stackedWin->addWidget(m_initConnectWin);
    m_stackedWin->addWidget(widget1);
    m_stackedWin->setCurrentIndex(0);

    QVBoxLayout *vLayout = new QVBoxLayout;
    vLayout->addWidget(m_titlebar);
    vLayout->addWidget(m_stackedWin);
    vLayout->addStretch();
    vLayout->setMargin(0);

    QWidget *widget2 = new QWidget(this);
    widget2->setLayout(vLayout);
    setCentralWidget(widget2);

    setAutoFillBackground(true);
    setBackgroundRole(QPalette::Base);

    m_copyToComputerButtonWidget = new CopyToComputerButtonWidget(this);
    m_copyToComputerButtonWidget->hide();

    connect(m_titlebar, &Titlebar::sigAboutWinShow, this, &MainWindow::slotAboutWinShow);
    connect(m_titlebar, &Titlebar::sigSearchResult, this, &MainWindow::onRecvSearchResult);
    connect(this, &MainWindow::sigClearSearchLine, m_titlebar, &Titlebar::onBackButtonClick);
    connect(this, &MainWindow::sigSearchUpdate, m_titlebar, &Titlebar::onReturnPressed);
    connect(m_titlebar, &Titlebar::sigSearchInitFail, this, &MainWindow::slotSearchInitFail);
    connect(m_initConnectWin, &InitConnectWin::sigUSBconnectBtnClicked, this, &MainWindow::slotUSBConnectOnClicked);
    connect(m_connectedTitleWin, &ConnectedTitleWin::sigDisconnectBtnClicked, this, &MainWindow::slotDisconnect);
    connect(m_connectedTitleWin, &ConnectedTitleWin::sigSetMobileWindow, this, &MainWindow::slotSetMobileWindow);
    connect(m_mobileFileList, &MobileFileList::sigPictureClicked, this, &MainWindow::slotItemButtonClicked);
    connect(m_mobileFileList, &MobileFileList::sigVideoClicked, this, &MainWindow::slotItemButtonClicked);
    connect(m_mobileFileList, &MobileFileList::sigMusicClicked, this, &MainWindow::slotItemButtonClicked);
    connect(m_mobileFileList, &MobileFileList::sigDocumentClicked, this, &MainWindow::slotItemButtonClicked);
    connect(m_mobileFileList, &MobileFileList::sigWeChatClicked, this, &MainWindow::slotItemButtonClicked);
    connect(m_mobileFileList, &MobileFileList::sigQQClicked, this, &MainWindow::slotItemButtonClicked);
    connect(m_mobileFileList, &MobileFileList::sigMobileStorageClicked, this,
            &MainWindow::slotCdMobileStorageDirectory);
    connect(m_copyToComputerButtonWidget, &CopyToComputerButtonWidget::sigChooseFilePath, this,
            &MainWindow::slotChooseFilePath);
}

void MainWindow::connectUI()
{
    if (!m_isConnect) {
        m_isConnect = true;
        m_downFileType = FileSyncManage::LIST_TYPE::TYPE_FILE_NUM;
        m_connectedTitleWin->setMobileName(m_connectInfo.deviceName);
        m_initConnectWin->setOnConnection(true);
        startLoadUI(50);
    }
    m_currentPath = "Home page";
}

void MainWindow::updateResult()
{
    if (m_downFileType == FileSyncManage::LIST_TYPE::TYPE_FILE_NUM) {
        QMap<QString, int> fileNumMap;
        if (m_fileSyncManage) {
            m_fileSyncManage->getItemCount(fileNumMap);
        }
        if (m_updateWin == WIN_FLAGE::WIN_INIT_MAIN) {
            stopLoadUI();
            if (m_initConnectWin != nullptr) {
                m_initConnectWin->setOnConnection(false);
            }
            m_mobileFileList->setItemCount(fileNumMap);
            m_stackedWin->setCurrentIndex(1);
            Q_EMIT sigConnected(m_connectInfo.deviceName);
        }
        if (m_updateWin == WIN_FLAGE::WIN_INIT_QQWECHAT) {
            m_mobileFileSecondWidget->setItemCount(fileNumMap);
            m_stackedMobileFileListWin->setCurrentIndex(1);
            m_loadAnimation->deleteLater();
            m_loadAnimation = nullptr;
        }
        if (m_updateWin == WIN_FLAGE::WIN_RETURN_MAIN) {
            m_mobileFileList->setItemCount(fileNumMap);
            m_stackedMobileFileListWin->setCurrentIndex(0);
            m_loadAnimation->deleteLater();
            m_loadAnimation = nullptr;
        }
    } else if (m_downFileType == FileSyncManage::LIST_TYPE::TYPE_MUSIC
               || m_downFileType == FileSyncManage::LIST_TYPE::TYPE_QQ_MUSIC
               || m_downFileType == FileSyncManage::LIST_TYPE::TYPE_WECHAT_MUSIC) {
        QList<FileInfo> list;
        m_fileSyncManage->getClassifiedFileList(m_downFileType, list);
        m_listItemWidget->setMusicData(list);
    } else if (m_downFileType == FileSyncManage::LIST_TYPE::TYPE_DOCUMENT
               || m_downFileType == FileSyncManage::LIST_TYPE::TYPE_QQ_DOCUMENT
               || m_downFileType == FileSyncManage::LIST_TYPE::TYPE_WECHAT_DOCUMENT) {
        QList<FileInfo> list;
        m_fileSyncManage->getClassifiedFileList(m_downFileType, list);
        m_listItemWidget->setDocumenData(list);
    } else {
        QList<FileInfo> list;
        m_fileSyncManage->getClassifiedFileList(m_downFileType, list);
        m_listItemWidget->setTimeLineData(list);
    }
}

void MainWindow::setScreenState(bool isScreenShow)
{
    stopLoadUI();
    if (m_connectedTitleWin != nullptr) {
        m_connectedTitleWin->setShowMobileWinBtn(isScreenShow);
    }
}

void MainWindow::initTransmissionDialog()
{
    m_transmissionDialog = new TransmissionDialog(this);
    connect(m_transmissionDialog, &TransmissionDialog::sigCancelAbort, this, &MainWindow::slotAbortTransmission);
    QRect availableGeometry = geometry();
    m_transmissionDialog->move(availableGeometry.center() - m_transmissionDialog->rect().center());
    m_transmissionDialog->show();
}

void MainWindow::isExistWidget()
{
    if (m_mobileStorageWidget != nullptr) {
        m_mobileStorageWidget->deleteLater();
        m_mobileStorageWidget = nullptr;
    }
    if (m_listItemWidget != nullptr) {
        m_listItemWidget->deleteLater();
        m_listItemWidget = nullptr;
    }
    if (m_mobileFileSecondWidget != nullptr) {
        m_mobileFileSecondWidget->deleteLater();
        m_mobileFileSecondWidget = nullptr;
    }
    if (m_loadAnimation != nullptr) {
        m_loadAnimation->deleteLater();
        m_loadAnimation = nullptr;
    }
    stopLoadUI();
}

void MainWindow::initMobileListWidget(int tag)
{
    m_listItemWidget = new MobileFileWidget(tag, this);
    connectMobileFileWidget();
    m_stackedMobileFileListWin->addWidget(m_listItemWidget);
    m_stackedMobileFileListWin->setCurrentIndex(1);
    m_listItemWidget->showLoadWin();
    m_fileSyncManage->updateFileInfo(m_downFileType);
}

void MainWindow::connectMobileFileWidget()
{
    connect(m_listItemWidget, &MobileFileWidget::sigModeChange, this, [=](QListView::ViewMode mode) {
        m_classificationMode = mode;
    });
    connect(m_listItemWidget, &MobileFileWidget::sigInitFinish, this, &MainWindow::slotDownThumb);
    connect(m_listItemWidget, &MobileFileWidget::sigUpdateClicked, this, &MainWindow::slotItemButtonClicked);
    connect(m_listItemWidget, &MobileFileWidget::sigMenuFilePath, this, &MainWindow::slotMenuFilePath);
    connect(m_listItemWidget, &MobileFileWidget::sigSelectAllDataList, this, &MainWindow::slotSelectDataList);
    connect(m_listItemWidget, &MobileFileWidget::sigShowMobileFileListWidget, this,
            &MainWindow::slotShowMobileFileListWidget);
    connect(m_listItemWidget, &MobileFileWidget::sigShowMobileFileSecondWidget, this,
            &MainWindow::slotShowMobileFileSecondWidget);

    connect(m_listItemWidget, &MobileFileWidget::sigSelectDataList, this, &MainWindow::slotSelectDataList);
    connect(m_listItemWidget, &MobileFileWidget::sigShowCopyButtonWidget, this, &MainWindow::slotShowCopyButtonWidget);
    connect(m_listItemWidget, &MobileFileWidget::sigHideCopyToComputerWidget, this,
            &MainWindow::slotHideCopyToComputerWidget);
}

void MainWindow::setToolTipWin(QString msg)
{
    TipWidget *tipWidget = new TipWidget();
    tipWidget->setParent(this);
    tipWidget->SetMesseage(msg);
}

void MainWindow::setLocalPathList(const QStringList &list)
{
    qInfo() << "get local peony menu send path list" << list;
    if (!m_isConnect) {
        TipWidget *tipWidget = new TipWidget();
        tipWidget->setParent(m_initConnectWin);
        tipWidget->SetMesseage(tr("Not currently connected, please connect"), nullptr, 20);
        qInfo() << "peony menu send: not current connect";
        return;
    }
    uploadLocalListPath("/Download", list);
}

void MainWindow::moveCopyToComputerWidget()
{
    m_copyToComputerButtonWidget->move(QPoint(398, 589));
}

void MainWindow::deleterUI()
{
    if (m_titlebar != nullptr) {
        delete m_titlebar;
        m_titlebar = nullptr;
    }
    if (m_initConnectWin != nullptr) {
        delete m_initConnectWin;
        m_initConnectWin = nullptr;
    }
    if (m_connectedTitleWin != nullptr) {
        delete m_connectedTitleWin;
        // system(common.toStdString().c_str());
        m_connectedTitleWin = nullptr;
    }
    if (m_mobileFileList != nullptr) {
        delete m_mobileFileList;
        m_mobileFileList = nullptr;
    }
    if (m_stackedWin != nullptr) {
        m_stackedWin->deleteLater();
        m_stackedWin = nullptr;
    }
}

void MainWindow::startLoadUI(int y)
{
    m_connectDialog = new ConnectDialog(this);
    m_connectDialog->move((this->width() - m_connectDialog->width()) >> 1,
                          ((this->height() - m_connectDialog->height()) >> 1) - y);
    m_connectDialog->show();
    m_timer = new QTimer(this);
    m_timer->setSingleShot(true);
    connect(m_timer, &QTimer::timeout, this, &MainWindow::slotConnectFailed, Qt::DirectConnection);
    m_timer->start(30000);
}
void MainWindow::stopLoadUI()
{
    if (m_connectDialog != nullptr) {
        m_connectDialog->deleteLater();
        m_connectDialog = nullptr;
    }
    if (m_timer != nullptr) {
        m_timer->stop();
        m_timer->deleteLater();
        m_timer = nullptr;
    }
    if (m_transmissionDialog != nullptr) {
        m_transmissionDialog->deleteLater();
        m_transmissionDialog = nullptr;
        setToolTipWin(tr("file download failed"));
    }
}

void MainWindow::slotVolumeConnected(QString volumeName)
{
    // todo
}

void MainWindow::slotVolumeDisconnected(QString volumeName)
{
    if (m_connectInfo.connectType == ConnectionService::ConnectType::USB && m_connectInfo.deviceName.isEmpty()) {
        qInfo() << m_connectInfo.deviceName << "disconnected";
        slotDisconnect();
    }
}

void MainWindow::slotWifiConnected(QString wifiIP)
{
    m_initConnectWin->setInterFaceCodeInfo(wifiIP);
}

void MainWindow::slotWifiDisConnected()
{
    m_initConnectWin->setInterFaceCodeInfo();
    if (m_connectInfo.connectType == ConnectionService::ConnectType::WIFI) {
        slotDisconnect();
    }
}

void MainWindow::slotConnect(const ConnectionService::ConnectionInfo &connectInfo)
{
    m_connectInfo = connectInfo;
    m_url.setUserName(m_connectInfo.usernamePwd.username);
    m_url.setPassword(m_connectInfo.usernamePwd.pwd);
    // 安卓连接埋点
    GenerateTools::buriedPoint(kabase::BuriedPoint::PT::KylinMobileAssistantAndroidConn);
    m_connectInfo.deviceName.remove(" ");
    connectUI();
    m_ftpClient = new FtpManager(this);
    connect(m_ftpClient, &FtpManager::sigFtpServerConnected, this, &MainWindow::slotFtpConnected);
    connect(m_ftpClient, &FtpManager::sigFtpConnectFailed, this, &MainWindow::slotConnectFailed);
    connect(m_ftpClient, &FtpManager::sigUpdateTransferProgress, this, &MainWindow::slotTransferProgress);
    connect(m_ftpClient, &FtpManager::sigCurrentDirectoryList, this, &MainWindow::slotCurrentDirectoryList);
    connect(m_ftpClient, SIGNAL(sigDownFileFail(QString)), this, SLOT(slotDownFileFail(QString)));
    connect(m_ftpClient, &FtpManager::sigFtpReconnected, this, [=]() {
        stopLoadUI();
    });

    if (m_connectInfo.connectType == ConnectionService::ConnectType::WIFI) {
        m_ftpClient->setTransferMode(QFtp::Active);
        m_url.setUrl("ftp://" + m_connectInfo.address + ":" + QString::number(WIFI_FTP_PORT));
    } else {
        m_ftpClient->setTransferMode(QFtp::Passive);
        m_url.setUrl("ftp://" + m_connectInfo.address + ":" + QString::number(USB_FTP_PORT));
    }
    m_ftpClient->setUrl(m_url);
    m_isServerConnect = true;
    m_ftpClient->connectFtpServer();
}

void MainWindow::slotDisconnect()
{
    clearConnectionInfo();
    Q_EMIT sigDisconnect();
    m_isConnect = false;
    m_uploadPath = "";
    m_updateWin = WIN_FLAGE::WIN_INIT_MAIN;
    m_downFileType = FileSyncManage::LIST_TYPE::TYPE_FILE_NUM;
    m_storageMode = QListView::IconMode;
    m_classificationMode = QListView::IconMode;
    m_index = 2;
    m_titlebar->hideSearchLine();
    m_initConnectWin->setOnConnection(false);
    m_stackedWin->setCurrentIndex(0);
    isExistWidget();
    if (m_copyToComputerButtonWidget->isVisible()) {
        m_copyToComputerButtonWidget->hide();
    }
    stopLoadUI();
    m_stackedMobileFileListWin->setCurrentIndex(0);
    if (m_isServerConnect) {
        disconnectService();
    }
}

void MainWindow::slotNotFountApk()
{
    qCritical() << "kylin-assistant not installed!";
    QMessageBox msgBox;
    msgBox.setText(tr("Please install kylin-assistant on the Android terminal!"));
    msgBox.setIcon(QMessageBox::Critical);
    msgBox.exec();
}

void MainWindow::slotConnectFailed()
{
    qInfo() << "Failed to connect device!";
    if (m_initConnectWin != nullptr) {
        m_initConnectWin->setOnConnection(false);
    }
    if (m_isConnect) {
        TipWidget *tipWidget = new TipWidget();
        tipWidget->setParent(this);
        tipWidget->SetMesseage(tr("Connection error"), nullptr, 20);
        slotDisconnect();
    }
}

void MainWindow::slotFtpConnected()
{
    bool flag = mountFtp(m_url.toString(), m_url.userName(), m_url.password(), MOUNT_DIR);
    if (!flag) {
        slotMountError(true, "d-bus service fail!");
    }
    m_isMountFtp = true;
    m_fileSyncManage = new FileSyncManage(m_connectInfo.uuid, m_url, this);
    connect(m_fileSyncManage, &FileSyncManage::sigDownFileFinish, this, &MainWindow::slotDownFileFinish);
    connect(m_fileSyncManage, &FileSyncManage::sigDownAllFileFinish, this, &MainWindow::slotDownAllFileFinish);
    connect(m_fileSyncManage, SIGNAL(sigDownFileFail(QString, QString)), this,
            SLOT(slotDownFileFail(QString, QString)));
    connect(m_fileSyncManage, &FileSyncManage::sigSearchInfoFinsh, m_titlebar, &Titlebar::onSearchInstalled);
    connect(m_fileSyncManage, &FileSyncManage::sigTempFileDownFinish, this, &MainWindow::slotDownTempFileFinish);
    m_fileSyncManage->updateFileInfo(FileSyncManage::LIST_TYPE::TYPE_FILE_NUM);
}

void MainWindow::slotCurrentDirectoryList(const QMap<QString, FileInfo> &filelist)
{
    if (m_isDbusOperation) {
        // dbus操作
        Q_EMIT sigFileInfoList(filelist);
        m_isDbusOperation = false;
    } else {
        isExistWidget();
        m_mobileStorageWidget = new MobileStorageWidget(filelist, m_currentPath, this);
        connect(m_mobileStorageWidget, &MobileStorageWidget::sigModeChange, this, [=](QListView::ViewMode mode) {
            m_storageMode = mode;
        });
        m_mobileStorageWidget->setMode(m_storageMode);
        m_stackedMobileFileListWin->addWidget(m_mobileStorageWidget);
        m_stackedMobileFileListWin->setCurrentIndex(1);

        connect(m_mobileStorageWidget, &MobileStorageWidget::sigFileName, this,
                &MainWindow::slotCdMobileStorageDirectory);
        connect(m_mobileStorageWidget, &MobileStorageWidget::sigShowMobileStorage, this,
                &MainWindow::slotShowMobileStorage);
        connect(m_mobileStorageWidget, &MobileStorageWidget::sigCurrentIndexPath, this,
                &MainWindow::slotCdMobileStorageDirectory);
        connect(m_mobileStorageWidget, &MobileStorageWidget::sigLocalPathList, this, &MainWindow::slotLocalPathList);
        connect(m_mobileStorageWidget, &MobileStorageWidget::sigUpdateClicked, this,
                &MainWindow::slotCdMobileStorageDirectory);
        connect(m_mobileStorageWidget, &MobileStorageWidget::sigMenuFileName, this, &MainWindow::slotMenuFilePath);
        connect(m_mobileStorageWidget, &MobileStorageWidget::sigSelectDataList, this, &MainWindow::slotSelectDataList);
        connect(m_mobileStorageWidget, &MobileStorageWidget::sigShowCopyButtonWidget, this,
                &MainWindow::slotShowCopyButtonWidget);
        connect(m_mobileStorageWidget, &MobileStorageWidget::sigHideCopyToComputerWidget, this,
                &MainWindow::slotHideCopyToComputerWidget);
    }
}

void MainWindow::slotTransferProgress(qint64 readBytes, qint64 totalBytes)
{
    if (!m_isDbusOperation) {
        if (m_transmissionDialog != nullptr) {
            m_transmissionDialog->setProgressBarRange(0, totalBytes);
            m_transmissionDialog->setProgressBarValue(readBytes);
            if (readBytes == totalBytes) {
                m_transmissionDialog->deleteLater();
                m_transmissionDialog = nullptr;
                setToolTipWin(m_tipMesseage);
                if (!m_uploadPath.isEmpty()) {
                    m_currentPath = m_uploadPath;
                    m_ftpClient->cdToDir(m_uploadPath);
                    m_uploadPath = "";
                    startLoadUI(0);
                }
            }
        }
    } else {
        if (readBytes == totalBytes) {
            m_isDbusOperation = false;
        }
    }
}

void MainWindow::slotDownFileFinish(QString flag, QString filepath)
{
    if (!flag.isEmpty()) {
        // flag不为空，一个缩略图下载完成
        if (m_listItemWidget != nullptr) {
            m_listItemWidget->setThumbanil(filepath);
        }
    }
}

void MainWindow::slotDownAllFileFinish(QString flag)
{
    if (flag.isEmpty()) {
        // flag为空，信息文件下载完成
        qInfo() << "File information update completed!";
        updateResult();
    } else {
        // 缩略图全部下载完成
        qInfo() << "All thumbnails downloaded.";
    }
}

void MainWindow::slotDownTempFileFinish(QString filePath)
{
    stopLoadUI();

    if (!filePath.isEmpty()) {
        FileInfo::fileOpen(filePath);
    } else {
        qInfo() << "Open file error, file path is null!";
    }
}

void MainWindow::slotDownFileFail(QString fileName, QString flag)
{
    Q_UNUSED(fileName);
    stopLoadUI();
    if (flag.isEmpty()) {
        slotConnectFailed();
    }
}

void MainWindow::slotDownFileFail(QString fileName)
{
    if (m_transmissionDialog != nullptr) {
        m_transmissionDialog->deleteLater();
        m_transmissionDialog = nullptr;
    }
    setToolTipWin(tr("file download failed"));
}

void MainWindow::slotMountError(bool isMount, QString error)
{
    qInfo() << "mountFtpError:" << error;
    if (isMount) {
        QMessageBox::warning(this, tr("Warning"), tr("Peony access can be error-prone"), QMessageBox::Ok);
    } else {
        setToolTipWin(tr("Umount failed"));
    }
}

void MainWindow::slotAboutWinShow()
{
    // kylin-mobile-assistant Version:
    m_aboutWindow = new kdk::KAboutDialog(this, QIcon::fromTheme("kylin-multi-collaboration"),
                                          QString(tr("mobile-assistant")), tr("Version:") + qApp->applicationVersion());
    m_aboutWindow->setAttribute(Qt::WA_DeleteOnClose);
    m_aboutWindow->setBodyText(tr("Mobile Assistant is an interconnection tool of Android device and Kirin operating "
                                  "system, which supports Android file synchronization, file transfer, screen "
                                  "mirroring and other functions, which is simple and fast to operate"));
    m_aboutWindow->setBodyTextVisiable(true);
    m_aboutWindow->setWindowModality(Qt::WindowModal);
    m_aboutWindow->setWindowModality(Qt::ApplicationModal);

    m_aboutWindow->show();
    m_aboutWindow->exec();
}

void MainWindow::onRecvSearchResult(const QMap<QString, FileInfo> &searchResult)
{
    qInfo() << "search by keyword";
    isExistWidget();
    m_mobileStorageWidget = new MobileStorageWidget(searchResult, "Search", this);
    connect(m_mobileStorageWidget, &MobileStorageWidget::sigModeChange, this, [=](QListView::ViewMode mode) {
        m_storageMode = mode;
    });
    m_mobileStorageWidget->setMode(m_storageMode);
    m_stackedMobileFileListWin->addWidget(m_mobileStorageWidget);
    m_stackedMobileFileListWin->setCurrentIndex(1);

    connect(m_mobileStorageWidget, &MobileStorageWidget::sigFileName, this, &MainWindow::slotCdMobileStorageDirectory);
    connect(m_mobileStorageWidget, &MobileStorageWidget::sigShowMobileStorage, this,
            &MainWindow::slotShowMobileStorage);
    connect(m_mobileStorageWidget, &MobileStorageWidget::sigCurrentIndexPath, this,
            &MainWindow::slotCdMobileStorageDirectory);
    connect(m_mobileStorageWidget, &MobileStorageWidget::sigLocalPathList, this, &MainWindow::slotLocalPathList);
    connect(m_mobileStorageWidget, &MobileStorageWidget::sigUpdateSearchClicked, this,
            &MainWindow::slotSearchUpdateClicked);
    connect(m_mobileStorageWidget, &MobileStorageWidget::sigMenuFileName, this, &MainWindow::slotMenuFilePath);
    connect(m_mobileStorageWidget, &MobileStorageWidget::sigSetLastWidget, this, &MainWindow::slotSetLastWidget);
    connect(m_mobileStorageWidget, &MobileStorageWidget::sigSelectDataList, this, &MainWindow::slotSelectDataList);
    connect(m_mobileStorageWidget, &MobileStorageWidget::sigShowCopyButtonWidget, this,
            &MainWindow::slotShowCopyButtonWidget);
    connect(m_mobileStorageWidget, &MobileStorageWidget::sigHideCopyToComputerWidget, this,
            &MainWindow::slotHideCopyToComputerWidget);
}

void MainWindow::slotUSBConnectOnClicked()
{
    m_connectionService->connectLocDev();
}

void MainWindow::slotSetMobileWindow()
{
    if (m_deviceManage == nullptr) {
        m_deviceManage = new DeviceManage();
        connect(m_deviceManage, &DeviceManage::sigScreenConnected, this, [=]() {
            setScreenState(true);
        });
        connect(m_deviceManage, &DeviceManage::sigSocketDisconnect, this, [=]() {
            setScreenState(false);
            m_connectionService->closeAbility();
            m_deviceManage->deleteLater();
            m_deviceManage = nullptr;
        });
    }
    if (m_connectionService->isSupportADB()) {
        BaseDevice::DeviceParams params;
        params.serial = m_connectionService->getDeviceSerial();
        params.maxFps = static_cast<quint32>(Config::getInstance().getMaxFps());
        params.localPort = USBPORT;
        params.screenIndex = getScreenIndex();
        m_deviceManage->connectDevice(params);
    } else {
        BaseDevice::DeviceParams params;
        params.serial = m_url.host();
        params.localPort = WIFIPORT;
        params.screenIndex = getScreenIndex();
        m_deviceManage->connectWifiDevice(params);
    }
    startLoadUI(50);
}

void MainWindow::updateCurrentPath(int text)
{
    switch (text) {
    case FILE_TYPE::QQPICTURE:
        m_currentPath = tr("QQPicture");
        break;
    case FILE_TYPE::QQVIDEO:
        m_currentPath = tr("QQVideo");
        break;
    case FILE_TYPE::QQMUSIC:
        m_currentPath = tr("QQMusic");
        break;
    case FILE_TYPE::QQDOCUMENT:
        m_currentPath = tr("QQDocument");
        break;
    case FILE_TYPE::WECHATPICTURE:
        m_currentPath = tr("WeChatPicture");
        break;
    case FILE_TYPE::WECHATVIDEO:
        m_currentPath = tr("WeChatVideo");
        break;
    case FILE_TYPE::WECHATMUSIC:
        m_currentPath = tr("WeChatMusic");
        break;
    case FILE_TYPE::WECHATDOCUMENT:
        m_currentPath = tr("WeChatDocument");
        break;
    case FILE_TYPE::PICTURE:
        m_currentPath = tr("Picture");
        break;
    case FILE_TYPE::VIDEO:
        m_currentPath = tr("Video");
        break;
    case FILE_TYPE::MUSIC:
        m_currentPath = tr("Music");
        break;
    case FILE_TYPE::DOCUMENT:
        m_currentPath = tr("Document");
        break;
    case FILE_TYPE::WECHAT:
        m_currentPath = tr("WeChat");
        break;
    case FILE_TYPE::QQ:
        m_currentPath = tr("QQ");
        break;
    case FILE_TYPE::HOMEPAGE:
        m_currentPath = "Home page";
        break;
    default:
        break;
    }
}

void MainWindow::slotItemButtonClicked(int text)
{
    int tag = text;
    updateCurrentPath(text);
    qInfo() << "Clicked " << tag;
    isExistWidget();
    if (tag == FILE_TYPE::QQPICTURE) {
        // 图片列表埋点
        GenerateTools::buriedPoint(kabase::BuriedPoint::PT::KylinMobileAssistantPictureList);
        m_downFileType = FileSyncManage::LIST_TYPE::TYPE_QQ_PICTURE;
        initMobileListWidget(FILE_TYPE::QQPICTURE);
    } else if (tag == FILE_TYPE::QQVIDEO) {
        // 视频列表埋点
        GenerateTools::buriedPoint(kabase::BuriedPoint::PT::KylinMobileAssistantVideoList);
        m_downFileType = FileSyncManage::LIST_TYPE::TYPE_QQ_VIDEO;
        initMobileListWidget(FILE_TYPE::QQVIDEO);
    } else if (tag == FILE_TYPE::QQMUSIC) {
        // 音频列表埋点
        GenerateTools::buriedPoint(kabase::BuriedPoint::PT::KylinMobileAssistantAudioList);
        m_downFileType = FileSyncManage::LIST_TYPE::TYPE_QQ_MUSIC;
        initMobileListWidget(FILE_TYPE::QQMUSIC);
    } else if (tag == FILE_TYPE::QQDOCUMENT) {
        // 文档列表埋点
        GenerateTools::buriedPoint(kabase::BuriedPoint::PT::KylinMobileAssistantDocList);
        m_downFileType = FileSyncManage::LIST_TYPE::TYPE_QQ_DOCUMENT;
        initMobileListWidget(FILE_TYPE::QQDOCUMENT);
    } else if (tag == FILE_TYPE::WECHATPICTURE) {
        // 图片列表埋点
        GenerateTools::buriedPoint(kabase::BuriedPoint::PT::KylinMobileAssistantPictureList);
        m_downFileType = FileSyncManage::LIST_TYPE::TYPE_WECHAT_PICTURE;
        initMobileListWidget(FILE_TYPE::WECHATPICTURE);
    } else if (tag == FILE_TYPE::WECHATVIDEO) {
        // 视频列表埋点
        GenerateTools::buriedPoint(kabase::BuriedPoint::PT::KylinMobileAssistantVideoList);
        m_downFileType = FileSyncManage::LIST_TYPE::TYPE_WECHAT_VIDEO;
        initMobileListWidget(FILE_TYPE::WECHATVIDEO);
    } else if (tag == FILE_TYPE::WECHATMUSIC) {
        // 音频列表埋点
        GenerateTools::buriedPoint(kabase::BuriedPoint::PT::KylinMobileAssistantAudioList);
        m_downFileType = FileSyncManage::LIST_TYPE::TYPE_WECHAT_MUSIC;
        initMobileListWidget(FILE_TYPE::WECHATMUSIC);
    } else if (tag == FILE_TYPE::WECHATDOCUMENT) {
        // 文档列表埋点
        GenerateTools::buriedPoint(kabase::BuriedPoint::PT::KylinMobileAssistantDocList);
        m_downFileType = FileSyncManage::LIST_TYPE::TYPE_WECHAT_DOCUMENT;
        initMobileListWidget(FILE_TYPE::WECHATDOCUMENT);
    } else if (tag == FILE_TYPE::PICTURE) {
        // 图片列表埋点
        GenerateTools::buriedPoint(kabase::BuriedPoint::PT::KylinMobileAssistantPictureList);
        m_downFileType = FileSyncManage::LIST_TYPE::TYPE_PICTURE;
        initMobileListWidget(FILE_TYPE::PICTURE);
    } else if (tag == FILE_TYPE::VIDEO) {
        // 视频列表埋点
        GenerateTools::buriedPoint(kabase::BuriedPoint::PT::KylinMobileAssistantVideoList);
        m_downFileType = FileSyncManage::LIST_TYPE::TYPE_VIDEO;
        initMobileListWidget(FILE_TYPE::VIDEO);
    } else if (tag == FILE_TYPE::MUSIC) {
        // 音频列表埋点
        GenerateTools::buriedPoint(kabase::BuriedPoint::PT::KylinMobileAssistantAudioList);
        m_downFileType = FileSyncManage::LIST_TYPE::TYPE_MUSIC;
        initMobileListWidget(FILE_TYPE::MUSIC);
    } else if (tag == FILE_TYPE::DOCUMENT) {
        // 文档列表埋点
        GenerateTools::buriedPoint(kabase::BuriedPoint::PT::KylinMobileAssistantDocList);
        m_downFileType = FileSyncManage::LIST_TYPE::TYPE_DOCUMENT;
        initMobileListWidget(FILE_TYPE::DOCUMENT);
    } else if (tag == FILE_TYPE::WECHAT || tag == FILE_TYPE::QQ) {
        // QQ微信图片列表埋点
        if (tag == FILE_TYPE::WECHAT) {
            GenerateTools::buriedPoint(kabase::BuriedPoint::PT::KylinMobileAssistantWechatFileList);
        } else {
            GenerateTools::buriedPoint(kabase::BuriedPoint::PT::KylinMobileAssistantQQFileList);
        }
        m_downFileType = FileSyncManage::LIST_TYPE::TYPE_FILE_NUM;
        m_updateWin = WIN_FLAGE::WIN_INIT_QQWECHAT;
        m_mobileFileSecondWidget = new MobileFileSecondWidget(text);
        //设置图片时间线的数据
        m_stackedMobileFileListWin->addWidget(m_mobileFileSecondWidget);
        m_loadAnimation = new LoadAnimation;
        m_loadAnimation->setHighLight();
        m_stackedMobileFileListWin->addWidget(m_loadAnimation);
        m_stackedMobileFileListWin->setCurrentIndex(m_index);
        connect(m_mobileFileSecondWidget, &MobileFileSecondWidget::sigItemButtonClicked, this,
                &MainWindow::slotItemButtonClicked);
        connect(m_mobileFileSecondWidget, &MobileFileSecondWidget::sigShowMobileFileListWidget, this,
                &MainWindow::slotShowMobileFileListWidget);
        connect(m_mobileFileSecondWidget, &MobileFileSecondWidget::sigUpdateClicked, this,
                &MainWindow::slotItemButtonClicked);
        m_fileSyncManage->updateFileInfo(m_downFileType);
    }
}

void MainWindow::slotCdMobileStorageDirectory(QString path)
{
    // 手机存储列表埋点
    GenerateTools::buriedPoint(kabase::BuriedPoint::PT::KylinMobileAssistantMobileStorage);
    m_currentPath = path;
    m_ftpClient->cdToDir(path);
    startLoadUI(0);
}

void MainWindow::slotDownThumb()
{
    if (m_downFileType == FileSyncManage::LIST_TYPE::TYPE_FILE_NUM) {
        return;
    }
    if (m_listItemWidget != nullptr) {
        m_listItemWidget->setMode(m_classificationMode);
    }
    if (m_downFileType == FileSyncManage::LIST_TYPE::TYPE_PICTURE
        || m_downFileType == FileSyncManage::LIST_TYPE::TYPE_VIDEO
        || m_downFileType == FileSyncManage::LIST_TYPE::TYPE_QQ_PICTURE
        || m_downFileType == FileSyncManage::LIST_TYPE::TYPE_QQ_VIDEO
        || m_downFileType == FileSyncManage::LIST_TYPE::TYPE_WECHAT_PICTURE
        || m_downFileType == FileSyncManage::LIST_TYPE::TYPE_WECHAT_VIDEO) {
        m_fileSyncManage->downThumb(m_downFileType);
    }
}

void MainWindow::slotMenuFilePath(QString filePath)
{
    // 打开文件埋点
    GenerateTools::buriedPoint(kabase::BuriedPoint::PT::KylinMobileAssistantOpenFile);
    m_fileSyncManage->downTempFile(filePath);
    startLoadUI(0);
}

void MainWindow::slotSetLastWidget()
{
    Q_EMIT sigClearSearchLine();
    qInfo() << "search previous path" << m_currentPath;
    if (m_currentPath == "Home page") {
        slotShowMobileStorage();
    } else {
        if (m_currentPath == tr("Picture")) {
            slotItemButtonClicked(FILE_TYPE::PICTURE);
        } else if (m_currentPath == tr("Video")) {
            slotItemButtonClicked(FILE_TYPE::VIDEO);
        } else if (m_currentPath == tr("Music")) {
            slotItemButtonClicked(FILE_TYPE::MUSIC);
        } else if (m_currentPath == tr("Document")) {
            slotItemButtonClicked(FILE_TYPE::DOCUMENT);
        } else if (m_currentPath.startsWith(tr("WeChat"))) {
            slotItemButtonClicked(FILE_TYPE::WECHAT);
        } else if (m_currentPath.startsWith(tr("QQ"))) {
            slotItemButtonClicked(FILE_TYPE::QQ);
        } else {
            slotCdMobileStorageDirectory(m_currentPath);
        }
    }
    slotHideCopyToComputerWidget();
}

void MainWindow::slotShowMobileFileListWidget()
{
    m_index = 2;
    m_updateWin = WIN_FLAGE::WIN_RETURN_MAIN;
    m_fileSyncManage->abortDownThumb();
    isExistWidget();
    m_loadAnimation = new LoadAnimation;
    m_loadAnimation->setHighLight();
    m_stackedMobileFileListWin->addWidget(m_loadAnimation);
    m_stackedMobileFileListWin->setCurrentIndex(2);
    m_downFileType = FileSyncManage::LIST_TYPE::TYPE_FILE_NUM;
    m_fileSyncManage->updateFileInfo(m_downFileType);
}

void MainWindow::uploadLocalListPath(QString itemName, const QStringList &localPath)
{
    GenerateTools::buriedPoint(kabase::BuriedPoint::PT::KylinMobileAssistantUploadFile);
    m_uploadPath = itemName;
    m_ftpClient->setTransferMode(QFtp::Passive);
    m_ftpClient->uploadAllFiles(localPath, itemName);
    m_tipMesseage = tr("Uploaded to") + itemName;
    initTransmissionDialog();
}

void MainWindow::slotLocalPathList(const QStringList &localPathList)
{
    // 上传文件埋点
    GenerateTools::buriedPoint(kabase::BuriedPoint::PT::KylinMobileAssistantUploadFile);
    m_uploadPath = m_currentPath;
    m_ftpClient->setTransferMode(QFtp::Passive);
    m_ftpClient->uploadAllFiles(localPathList, m_currentPath);
    m_tipMesseage = tr("Uploaded to") + m_currentPath;
    initTransmissionDialog();
}

void MainWindow::slotShowMobileFileSecondWidget(int indexPath)
{
    m_fileSyncManage->abortDownThumb();
    m_index = 3;
    slotItemButtonClicked(indexPath);
}

void MainWindow::slotShowMobileStorage()
{
    isExistWidget();
    m_currentPath = "Home page";
    m_stackedMobileFileListWin->setCurrentIndex(0);
}

void MainWindow::slotChooseFilePath(QString chooseFilePath, const QList<FileInfo> &selectFileNameList)
{
    qInfo() << "choose path" << chooseFilePath << "select file name list size" << selectFileNameList.size();
    QStringList listName;
    for (int i = 0; i < selectFileNameList.size(); i++) {
        listName << selectFileNameList.at(i).name();
    }
    qInfo() << "select file name list " << listName;
    if (listName.isEmpty()) {
        setToolTipWin(tr("file download failed"));
        return;
    }
    // 下载文件埋点
    GenerateTools::buriedPoint(kabase::BuriedPoint::PT::KylinMobileAssistantDownloadFile);
    m_ftpClient->downAllFiles(selectFileNameList, chooseFilePath);
    m_tipMesseage = tr("Downloaded to") + chooseFilePath;
    initTransmissionDialog();
}

void MainWindow::slotAbortTransmission()
{
    m_ftpClient->abort();
    if (m_transmissionDialog != nullptr) {
        delete m_transmissionDialog;
        m_transmissionDialog = nullptr;
    }
    startLoadUI(0);
}
void MainWindow::slotShowCopyButtonWidget()
{
    if (m_copyToComputerButtonWidget->isVisible()) {
        moveCopyToComputerWidget();
    } else {
        moveCopyToComputerWidget();
        m_copyToComputerButtonWidget->show();
        m_copyToComputerButtonWidget->raise();
    }
}

void MainWindow::slotHideCopyToComputerWidget()
{
    if (m_copyToComputerButtonWidget->isVisible()) {
        m_copyToComputerButtonWidget->hide();
    }
}

void MainWindow::slotSelectDataList(const QList<FileInfo> &fileList)
{
    qInfo() << "select list size" << fileList.size();
    m_copyToComputerButtonWidget->getSelectDataList(fileList);
}

void MainWindow::slotSearchInitFail()
{
    if (m_fileSyncManage != nullptr) {
        m_fileSyncManage->downloadSearch();
    }
}

void MainWindow::slotSearchUpdateClicked()
{
    m_currentPath = "Home page";
    Q_EMIT sigSearchUpdate();
    slotHideCopyToComputerWidget();
}

int MainWindow::getScreenIndex()
{
    QDesktopWidget *desktopWidget = QApplication::desktop();
    for (int i = 0; i < desktopWidget->screenCount(); i++) {
        if (desktopWidget->screenGeometry(i).contains(this->geometry())) {
            return i;
        }
    }
}
